const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");

// 扫码快速退包装物
router.post('/scan/toBack', async ctx => {
    let body = ctx.request.body
    let tenantId = ctx.user.tenantId;
    try {
        let code = body.code;
        let codeArr = code.split('-');
        if (codeArr.length !== 2) {
            return ctx.err('票号错误');
        }
        let billId = codeArr[1];
        // 票号信息
        let data = await db.query(`select id,arrears,billType,billDate,billState,billNo,buName,buId,salesId,salesName,deliverIds,deliverNames,remark
                                   from v_invoice where id=${billId} and tenantId=${tenantId}`,{type: QueryTypes.SELECT, plain: true})
        if (!data) {
            return ctx.err('未找到票据');
        }
        if (data.billState === 'del') {
            return ctx.err('票据已删除');
        }
        if (data.billType !== 'SALE') {
            return ctx.err('非销售票据');
        }
        // 仓库
        let oldList = await db.query(`select * from v_main_info where iid=${billId}`, {type: QueryTypes.SELECT})
        let locationId = oldList[0].locationId;
        let locationName = oldList[0].locationName;
        let sql = `select a.price,b.id as invId,b.name invName,b.spec,b.unit1 unit,b.unit1,b.unit2,'' qty, ${locationId} as locationId,'${locationName}' as locationName, 0 amount from goods_back a inner join v_goods b on a.invId=b.id and a.tenantId=${tenantId}` ;
        // 包装物信息
        data.goods = await db.query(sql, {type: QueryTypes.SELECT})
        data.oldList = oldList;
        // 如果已有历史关联
        let sql1 = `SELECT count(*) total from invoice_back where oldIid=${billId}`;
        let to = await db.query(sql1, {type: QueryTypes.SELECT, plain: true})
        data.hasHist = to.total
        return ctx.suc('', data);
    } catch (e) {
        return ctx.err(e);
    }
})


module.exports = router;
